<template>
  <div class="flex gui-paddingn">
    <div class="layout-left mainbg7 c333 mr10">
      <div class="form-itembox gui-padding">
        <div class="form-item">
          <div>
            <k-uploader ref="uploadRef" v-model="form.img"></k-uploader>
          </div>
        </div>
        <div class="flex" style="flex-wrap: wrap;justify-content: space-between;flex-direction: column">
          <div class="form-item">
            <div class="form-label">课程标题:</div>
            <div><input type="text" class="form-input" v-model="form.title" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">请选择栏目:</div>
            <div>
              <select class="form-select" placeholder="请选择栏目" @change="handleSelectChannel(form)"
                      v-model="form.channelId">
                <option value="">请选择</option>
                <template v-for="(item,index) in channelList" :key="index">
                  <option :value="item.id">{{ item.title }}-{{ item.id }}</option>
                </template>
              </select>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">课程分类:</div>
            <div>
              <select class="form-select" v-model.number="form.categoryId" placeholder="请选择栏目">
                <option value="">请选择</option>
                <option :value="item.id" v-for="(item,index) in categoryListFilter">{{ item.title }}</option>
              </select>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">选择老师:</div>
            <div>
              <select class="form-select" placeholder="选择老师" @change="handleSelectTeacher()" v-model="form.userid">
                <option value="">请选择</option>
                <template v-for="(item,index) in teacherList" :key="index">
                  <option :value="item.id">{{ item.nickname }}</option>
                </template>
              </select>
              <input v-model="form.username" type="hidden"/>
              <input v-model="form.avatar" type="hidden"/>
              <input v-model="form.uuid" type="hidden"/>
              <input v-model="form.userid" type="hidden"/>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">课程价格:</div>
            <div><input type="text" class="form-input" v-model="form.price" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">课程原价:</div>
            <div><input type="text" class="form-input" v-model="form.realprice" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">课程时长:</div>
            <div><input type="text" class="form-input" v-model="form.stimer" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">课程短路径:</div>
            <div><input type="text" class="form-input" v-model="form.path" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">课程外链:</div>
            <div><input type="text" class="form-input" v-model="form.url" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">专栏ID:</div>
            <div><input type="text" class="form-input" v-model.number="form.specialId" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">排序号:</div>
            <div><input type="text" class="form-input" v-model.number="form.sorted" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">课程浏览数:</div>
            <div><input type="text" class="form-input" v-model.number="form.viewcount" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">课程收藏数:</div>
            <div><input type="text" class="form-input" v-model.number="form.favNum" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">购买人数:</div>
            <div><input type="text" class="form-input" v-model.number="form.buyNum" placeholder="请填写"></div>
          </div>
          <div class="form-item ">
            <div class="form-label">课程网盘:</div>
            <div><input type="text" class="form-input" v-model="form.panLink" placeholder="请填写"></div>
          </div>
          <div class="form-item ">
            <div class="form-label">课程网盘密码:</div>
            <div><input type="text" class="form-input" v-model="form.panPwd" placeholder="请填写"></div>
          </div>
          <div class="form-item">
            <div class="form-label">课程标签:</div>
            <div><input type="text" class="form-input" v-model="form.tags" placeholder="请填写（多个逗号分割）"></div>
          </div>
          <div class="form-item">
            <div class="form-label">课程描述:</div>
            <div><textarea type="text" class="form-input" v-model="form.description" placeholder="请填写"></textarea>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">课程通知:</div>
            <div><textarea type="text" class="form-input" v-model="form.noticeMsg" placeholder="请填写"></textarea>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">关联栏目:</div>
            <div><input type="text" class="form-input" v-model="form.channelIds" placeholder="请填写"></div>
          </div>
        </div>
        <div class="flex" style="flex-wrap: wrap;flex-direction: column">
          <div class="form-item">
            <div class="form-label">课程状态:</div>
            <div>
              <label><input type="radio" v-model.number="form.status" :value="1" placeholder="请填写">发布</label>
              <label class="ml20"><input type="radio" v-model="form.status" :value="0"  placeholder="请填写">未发布</label>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">是否允许评论:</div>
            <div>
              <label><input type="radio" v-model.number="form.commentFlag" :value="1" placeholder="请填写">允许</label>
              <label class="ml20"><input type="radio" v-model="form.commentFlag" :value="0" placeholder="请填写">不允许</label>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">是否最新:</div>
            <div>
              <label><input type="radio" v-model.number="form.newFlag" :value="1" placeholder="请填写">最新</label>
              <label class="ml20"><input type="radio" v-model="form.newFlag" :value="0"
                                         placeholder="请填写">不最新</label>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">是否热门:</div>
            <div>
              <label><input type="radio" v-model.number="form.hotFlag" :value="1" placeholder="请填写">热门</label>
              <label class="ml20"><input type="radio" v-model="form.hotFlag" :value="0" placeholder="请填写">不热门</label>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">是否免费:</div>
            <div>
              <label><input type="radio" v-model.number="form.payFlag" :value="1" placeholder="请填写">免费</label>
              <label class="ml20"><input type="radio" v-model="form.payFlag" :value="2"  placeholder="请填写">收费</label>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">是否展示:</div>
            <div>
              <label><input type="radio" v-model.number="form.showFlag" :value="1" placeholder="请填写">展示</label>
              <label class="ml20"><input type="radio" v-model="form.showFlag" :value="0" placeholder="请填写">不展示</label>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">是否完成:</div>
            <div>
              <label><input type="radio" v-model.number="form.finished" :value="1" placeholder="请填写">已完成</label>
              <label class="ml20"><input type="radio" v-model="form.finished" :value="0" placeholder="请填写">未完成</label>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">是否有章节:</div>
            <div>
              <label><input type="radio" v-model.number="form.chapterFlag" :value="1"  placeholder="请填写">无章节</label>
              <label class="ml20"><input type="radio" v-model="form.chapterFlag" :value="2" placeholder="请填写">有章节</label>
            </div>
          </div>
          <div class="form-item">
            <div class="form-label">卡片类型:</div>
            <div>
              <label><input type="radio" v-model.number="form.ntype" :value="1" placeholder="请填写">手册</label>
              <label class="ml20"><input type="radio" v-model="form.ntype" :value="2" placeholder="请填写">视频</label>
            </div>
          </div>
          <div class="mt10 flex justify-center gui-padding mainbg7" style="position: fixed;bottom:0;right:0;left:0;">
            <a href="/admin/note" class="back-btn">返回</a>
            <a v-if="form.id && form.chapterFlag == 2" :href="'/note/add?id='+form.id" class="back-btn">添加章节</a>
            <a v-if="form.id" :href="'/note/'+(form.chapterFlag==1?'page':'detail')+'/'+form.id" target="_blank"
               class="back-btn">预览</a>
            <a v-if="form.id" href="javascript:void(0);" @click.prevent="handleOpenDidlog" class="back-btn">设置视频</a>
            <button class="save-btn" @click.prevent="handleSubmit">{{ form.id ? '编辑' : '保存' }}</button>
          </div>
        </div>
      </div>
    </div>
    <div class="layout-right" style="flex:1">
      <div @paste="paste" id="test-editor"></div>
    </div>
    <teleport to="body">
      <settingvideo :edit-obj="editObj" :clist="chapterList" ref="settingRef"></settingvideo>
    </teleport>
  </div>
</template>
<script setup>
import settingvideo from "@/pages/note/settingvideo.vue";
let testEditor = null;
const uploadRef = ref({});
const router = useRouter()
const chapterList = ref([])
const settingRef = ref([])
const editObj = ref({})
let timer = null
const timercount = ref(0)
var submitFileFlag = false
const form = ref({
  id: "",
  title: "",
  tags: "",
  content: "",
  htmlContent: "",
  description: "",
  viewcount: 0,
  commentFlag: 1,
  specialId: "",
  status: 1,
  img: "",
  favNum: 0,
  commentNum: 0,
  stimer: "0",
  channelIds: "",
  price: 0,
  realprice: 0,
  notetype: 1,
  newFlag: 0,
  hotFlag: 0,
  pushFlag: 0,
  noticeMsg: "",
  likeNum: 0,
  sorted: 1,
  vipFlag: 1,
  buyNum: 0,
  panLink: "",
  panPwd: "",
  payFlag: 1,
  finished: 0,
  showPrice: 1,
  path: "",
  ntype: 2,
  channelId: "",
  channelName: "",
  categoryName: "",
  categoryId: "",
  url: "",
  chapterFlag: 1,
  videoinfo: "",
  avatar: "",
  uuid: "",
  username: "",
  videoid: "",
  clientLink: "",
  clientLinkName: "",
  clientLinkImg: "",
  qqLinkCode: "",
  qqLinkName: "",
  qqLinkImg: "",
  weixinLink: "",
  weixinLinkName: "",
  weixinLinkImg: "",
  clientFlag: "",
  weixingzcode: "",
  weixingzimg: "",
  opengz: "",
  otherinfo: "",
  userid: "",
})

const channelList = ref([])
const teacherList = ref([])
const categoryList = ref([])
const categoryListFilter = ref([])

const handleSelectChannel = (item) => {
  form.value.channelName = channelList.value.find(c => c.id == form.value.channelId).title
  categoryListFilter.value = categoryList.value.filter(cc => cc.channelId == form.value.channelId)
}

const handleSelectTeacher = () => {
  var obj = teacherList.value.find(c => c.id = form.value.channelId)
  form.value.avatar = obj.avatar
  form.value.uuid = obj.uuid
  form.value.username = obj.username
  form.value.userid = obj.id
}

const handleOpenDidlog = async () => {
  settingRef.value.handleOpen(form.value.id, chapterList.value)
}

const handleLoadChannel = async () => {
  var items = sessionStorage.getItem("cc-channelList")
  if (!items) {
    const resp = await useLoadChannelList()
    channelList.value = resp.data
    sessionStorage.setItem("cc-channelList", JSON.stringify(resp.data))
  } else {
    channelList.value = JSON.parse(items)
  }
}

const handleLoadTeacher = async () => {
  const resp = await useLoadTeacherApi()
  teacherList.value = resp.data
}

const handleLoadCategories = async () => {
  const resp = await useLoadNoteCategoriesAllApi()
  categoryList.value = resp.data
}

const handleSubmit = async () => {
  await useLoginDialog()
  try {
    const resp = await useNoteSaveUpdateVideoApi(form.value)
    if (!form.value.id) {
      window.location.href = "/note/base?id=" + resp.data
    } else {
      useMessage().success("编辑成功")
    }
  } catch (e) {
    useMessage().error(e.message)
  }
}

const handleLoadDetail = async () => {
  await handleLoadChannel()
  await handleLoadTeacher()
  await handleLoadCategories()
  const resp = await useLoadNoteDetail(router.currentRoute.value.query.id);
  form.value = resp.data
  form.value.id = router.currentRoute.value.query.id
  categoryListFilter.value = categoryList.value.filter(cc => cc.channelId == resp.data.channelId)
  testEditor.setMarkdown(resp.data.content)
  chapterList.value = resp.data.chapterList
  editObj.value.noteId = resp.data.id
  editObj.value.chapterTitle = resp.data.title
  uploadRef.value.initFileList(resp.data)
}

const paste = function (event) {
  var cdata = (event.clipboardData || window.clipboardData);
  var items = cdata.items;
  if (items && items.length) {
    try {
      if (submitFileFlag) {
        useMessage().error("别太着急，慢一点!");
        return;
      }
      submitFileFlag = true
      var reader = new FileReader();
      var file = items[0].getAsFile()
      try {
        reader.readAsDataURL(file);
        reader.onload = function (event) {
          var formData = new FormData();
          formData.append('editormd-image-file', file)
          var xhr = new XMLHttpRequest();
          xhr.addEventListener("load", uploadComplete, false);
          xhr.addEventListener("error", uploadFailed, false);
          xhr.open('POST', "http://localhost:8089/api/v1/oss/upload/note");
          xhr.send(formData);

          function uploadComplete(evt) {
            var json = evt.target.responseText
            json = (typeof JSON.parse !== "undefined") ? JSON.parse(json) : eval("(" + json + ")");
            if (json.success == 1) {
              testEditor.replaceSelection("![](" + json.url + ")");
              useMessage().success("粘贴成功")
              submitFileFlag = false;
              handleSubmit()
            }
          }

          function uploadFailed() {
            submitFileFlag = false;
            useMessage().error("上传失败！请重试！");
          }
        }
      } catch (e) {
        submitFileFlag = false;
      }
    } catch (err) {
      submitFileFlag = false;
    }
  }
}


const handleSetintervalSave = () => {
  if (timer) {
    timercount.value = 0
    clearInterval(timer)
  }

  timer = setInterval(() => {
    timercount.value++
    if (timercount.value > 0 && timercount.value % 3 == 0) {
      handleSubmit()
    }
  }, 1000)
}

// 编辑节

onMounted(() => {
  document.addEventListener("keydown", function (e) {
    if (e.ctrlKey && e.key === 's') {
      handleSetintervalSave()
      e.preventDefault();
    }
  })
  // 选中的内容替换
  //testEditormd.replaceSelection("$$$$$$$$$");
  // 在光标处插入
  //testEditormd.insertValue("????");
  // testEditor.getMarkdown();       // 获取 Markdown 源码
  // testEditor.getHTML();           // 获取 Textarea 保存的 HTML 源码
  // testEditor.getPreviewedHTML();  // 获取预览窗口里的 HTML，在开启 watch 且没有开启 saveHTMLToTextarea 时使用
  testEditor = editormd("test-editor", {
    width: "100%",
    fontSize: "14px",
    height: "calc(100vh - 100px)",
    placeholder: "请输入笔记正文内容...",
    syncScrolling: "single",
    path: "/editormd/lib/",
    saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
    tocm: true,
    tocContainer: "",
    tocDropdown: false,
    tocStartLevel: 1,     // Parse beginning of H2, Default value 1
    emoji: true,
    tex: true,                   // 开启科学公式TeX语言支持，默认关闭
    flowChart: true,             // 开启流程图支持，默认关闭
    sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
    //图片上传
    imageUpload: true,
    imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
    imageUploadURL: "http://localhost:8089/api/v1/oss/upload/note", // 对接后端请求
    onload: function () {
      handleLoadDetail()
    },
    delay: 300,
    onchange: function (e) {
      form.value.content = testEditor.getMarkdown()
      form.value.htmlContent = testEditor.getHTML()
    },
    /*指定需要显示的功能按钮*/
    toolbarIcons: function () {
      return ["undo", "redo", "|", "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "image", "|", "h1", "h2", "h3", "h4", "h5", "h6", "|", "list-ul", "list-ol", "|", "link", "reference-link", "code", "code-block", "table", "datetime", "|", "goto-line", "watch", "preview", "fullscreen", "|", "testIcon", "|", "layoutmd"]
    },
    toolbarIconTexts: {
      testIcon: "模板",  // 如果没有图标，则可以这样直接插入内容，可以是字符串或HTML标签
      layoutmd: "<a href='https://www.kuangstudy.com/bbs/1356475333565587458' target='_blank'>MarkDown指南</a>"
    },
    toolbarHandlers: {
      testIcon: function (cm, icon, cursor, selection) {
        // 替换选中文本，如果没有选中文本，则直接插入
        cm.replaceSelection(document.getElementById("template").value);
        // 如果当前没有选中的文本，将光标移到要输入的位置
        if (selection === "") {
          cm.setCursor(cursor.line, cursor.ch + 1);
        }
      },
      layoutmd: function (cm, icon, cursor, selection) {

      },
    },
    onfullscreen: function () {
    },
    onfullscreenExit: function () {
    },
    onwatch: function () {
    }
  });
})

definePageMeta({
  middleware: ["md-auth"],
  layout: "detail"
})
</script>

<style scoped lang="scss">
.layout-left {
  width: 20%
}

.form-itembox {
  width: 100%;
  height: calc(100vh - 80px);
  overflow: auto;

  .form-item.w100 {
    width: 100%;
  }

  .form-item.w33 {
    width: 32%;
  }

  .form-item.w50 {
    width: 49.5%;
  }

  .form-item {
    margin-bottom: 8px;

    .form-label {
      font-weight: bold;
      margin-bottom: 10px;
    }

    .form-textarea,
    .form-select,
    .form-input {
      border: 1px solid #ddd;
      width: 100%;
      padding: 4px 12px;
      border-radius: 6px;
    }
  }
}

.save-btn,
.back-btn {
  background: #45c985;
  color: #fff;
  margin-right: 10px;
  padding: 3px 30px;
  border-radius: 4px;
}

.back-btn {
  background: #eee;
  color: #333
}
</style>